// 合同院内
<template>
  <div class="module_">
    <div class="mb16">
      <back />
    </div>
    <div class="pl8 flex-ver flex-1">
      <h4 class="mb8">基本信息</h4>
      <table class="table_ mb24">
        <tr>
          <td>合同名称</td>
          <td class="fb">{{info.name}}</td>
          <td>合同编号</td>
          <td class="fb">{{info.contract_code}}</td>
        </tr>
        <tr>
          <td>负责人</td>
          <td class="fb">{{info.leader_info?info.leader_info.name:''}}</td>
          <td>所属科室</td>
          <td class="fb">{{info.department?info.department.name:''}}</td>
        </tr>
        <tr>
          <td>项目经费</td>
          <td class="fb">{{info.project_funds}}万元</td>
          <td>总院内经费</td>
          <td class="fb">{{info.hospital_funds}}万元</td>
        </tr>
      </table>
      <div class="flex-space-between mb8">
        <h4>院内经费记录</h4>
        <div class="flex">
          <!-- v-permission="{action:'合同院内添加',effect:'delete'}" -->
          <el-button v-if="info.add" class="mr8" size="medium" type="primary"
            @click="handle(null,{},3)">添加院内经费记录</el-button>
          <exportExcel :getList='true' :options="{contracts_id}" :apiFn="Apicontracthospitalrecord "
            :name='info.name + "院内经费记录"' :self="true" :dataFn='dataFn' />
        </div>
      </div>
      <el-table :data="tableData" class="flex-1" height="100%" size="medium" border highlight-current-row
        v-loading="tableLoading" stripe @sort-change="tableSortChange">
        <el-table-column align="center" v-for="(item,i) in headerList" :key="item.prop" :prop="item.prop"
          :label="item.label + (item.unit || '')" :min-width="item.width" :fixed="i === 0 ? true: false"
          show-overflow-tooltip sortable="custom">
          <template slot-scope="scope">
            <template v-if="item.prop === 'departments_id'">
              {{ scope.row.department?scope.row.department.name:'' }}
            </template>
            <template v-else-if="item.prop === 'review_status'">
              <span v-if="scope.row.review_status === 2"
                class="c-red">{{reviewStatusObj[scope.row.review_status]}}：{{scope.row.review_comment}}</span>
              <span v-else>{{reviewStatusObj[scope.row.review_status]}}</span>
            </template>
            <template v-else>
              {{ scope.row[item.prop] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="135">
          <div class="flex-justify-end" slot-scope="scope">
            <el-tooltip effect="dark" content="审核" placement="bottom-end" v-show="scope.row.review_status == 0">
              <el-button v-permission="{action:'合同院内审核',effect:'delete'}" type="primary"
                @click="examine_btns(scope.row,1)" size="small" icon="el-icon-help" circle></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="修改信息" placement="bottom-end">
              <el-button v-if="info.add" size="small"
                @click="handle(scope.$index, scope.row,2)" icon="el-icon-edit" circle></el-button>
            </el-tooltip>
            <!-- v-permission="{action:'合同院内删除',effect:'delete'}" -->
            <el-tooltip effect="dark" content="删除" placement="bottom-end">
              <el-button v-if="info.add && scope.row.delete"  size="small" type="danger"
                @click="deleteUser(scope.$index, scope.row)" icon="el-icon-delete" circle></el-button>
            </el-tooltip>
          </div>
        </el-table-column>
      </el-table>

      <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    </div>

    <el-dialog :visible.sync="editFormVisible" width="400px" @close='dialogClose'
      :close-on-click-modal='false' :close-on-press-escape='false'>
      <h2 slot="title" class="tx-c">{{dialogTitle}}</h2>
      <el-form autocomplete="off" label-width="100px" :model="editForm" class="form_flex">
        <el-form-item v-for="(v, i) in editHeaderList" :key="i" :label="v.label" :class="v.required ? 'tip' : ''">
          <inputSearch v-if="v.prop === 'departments_id'" ref="departmentSearch" type="departments"
            @onChange='departmentsChange' />
          <inputSearch  v-else-if="v.prop === 'agent_name'" ref="agentSearch" @onChange='agentChange' :middleList="middleList" />
          <el-date-picker v-else-if="v.prop === 'receive_time'" size="medium" v-model="editForm[v.prop]" type="date"
            format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期时间">
          </el-date-picker>
          <el-input v-else size="medium" :type="v.type" autosize clearable v-model="editForm[v.prop]"
            @mousewheel.native.prevent
            :placeholder="'请输入' + v.label">
            <template v-if="v.prop === 'amount'" slot="append">万元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>

    <!-- 审核 -->
    <examine ref="examine" @submit='examineSubmit' :item='examine_item' />
  </div>
</template>

<script>
  import {
    Apicontracthospitalrecord,
    ApicontracthospitalrecordAdd,
    ApicontracthospitalrecordPut,
    ApicontracthospitalrecordDel,
    ApicontracthospitalrecordCheck,
    ApicontractfundsInfo
  } from '@/api'
  import {
    reviewStatus,
    reviewStatusObj
  } from '@/assets/js'
  import {
    debounce,
    adminShow
  } from "@/utils/index";
  import dataFn from '../js/exportFiles'
  export default {
    name: 'projectArrival',
    computed: {
      editHeaderList() {
        let list = this.headerList.filter(item => item.prop !== "review_status", )
        return list.sort((a, b) => b.required - a.required)
      }
    },
    data() {
      return {
        Apicontracthospitalrecord,
        dataFn,
        adminShow: adminShow(),
        contracts_id: this.$route.query.id,
        reviewStatus,
        reviewStatusObj,
        info: {
          department: {},
        },
        tableData: [],
        editFormVisible: false,
        editForm: {}, //修改或者查看详情

        pageparm: {
          page: 1,
          perPage: 20,
          total: null,
          sort_str: null,
          sort_order: 'desc',
        },
        tableLoading: false,
        btnLoading: false,

        headerList: [{
          prop: "departments_id",
          label: "科室",
          type: "text",
          width: "180",
          required: true,

        }, {
          prop: "review_status",
          label: "状态",
          type: "text",
          width: "160",
          required: true,

        }, {
          prop: "voucher_no",
          label: "凭单号",
          type: "text",
          width: "180",
          required: false,

        }, {
          prop: "amount",
          label: "金额",
          unit: "(万元)",
          type: "number",
          width: "170",
          required: true,

        }, {
          prop: "receive_time",
          label: "到账时间",
          type: "text",
          width: "150",
          required: true,

        }, {
          prop: "account",
          label: "财务账号",
          type: "text",
          width: "200",
          required: false,

        },{
          prop: "agent_name",
          label: "经办人",
          type: "text",
          width: "150",
          required: false,
      }],
        rules: ['departments_id', 'amount', 'receive_time'],

        examine_id: null, //审核id
        examine_item: {
          view: false
        },
        dialogTitle: '',
        middleList:[],
      }
    },
    mounted() {
      this.pageparm.contracts_id = this.contracts_id
      this.getInfo()
      this.getList()
    },
    methods: {
      getInfo() {
        ApicontractfundsInfo(this.contracts_id).then(({
          data
        }) => {
          this.info = data
        })
      },
      dialogClose() {
        this.$refs.departmentSearch[0].clear()
        this.$refs.agentSearch[0].clear()
      },
      examineSubmit(options) {
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        options.id = this.examine_id
        options.contracts_id = this.contracts_id
        ApicontracthospitalrecordCheck(options, options.id).then(res => {
          this.getInfo()
          this.getList()
        }).catch(() => {
          this.$message.error('服务器错误，请重新提交');
        }).finally(() => {
          loading.close()
        })
      },
      examine_btns(item, i) {
        this.examine_id = item.id
        if (i > 1) {
          this.examine_item.review_status = item.review_status
          this.examine_item.review_comment = item.review_comment
          this.examine_item.view = true
        } else {
          this.examine_item.view = false
        }
        this.$refs.examine.examineShow = true

      },
      tableSortChange(column) {
        if (column.order === "descending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "desc";
        } else if (column.order === "ascending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "asc";
        } else {
          this.pageparm.sort_str = null;
          this.pageparm.sort_order = null;
        }
        this.getList()
      },
      //分页
      callFather(pageparm) {
        this.pageparm.page = pageparm.page
        this.pageparm.perPage = pageparm.perPage
        this.getList()
      },
      getList() {
        this.tableLoading = true
        Apicontracthospitalrecord(this.pageparm).then(({
          data,
          page
        }) => {
          this.tableData = data || []
          this.pageparm.total = page.total
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      handle(index, value, i) {
        this.editForm = {
          ...value
        }
        this.editFormVisible = true
        this.dialogTitle = '添加院内经费记录'
        if (i == 2) {
          this.dialogTitle = '编辑院内经费记录'
          delete this.editForm.review
          this.$nextTick(() => {
            this.$refs.departmentSearch[0].departments_id = value.departments_id
            if(value.agent_id) this.middleList = [{employees_id: value.agent_id,employee: { name: value.agent_name }}];
          })
        } else {
          if (!this.adminShow) {
            this.editForm.departments_id = this.$store.state.userInfo.department_id
          }else{
            this.editForm.departments_id = this.info.departments_id
          }
          this.$nextTick(() => {
            this.$refs.departmentSearch[0].departments_id = this.editForm.departments_id
          })
        }
      },
      departmentsChange(id) {
        this.editForm.departments_id = id
      },
      agentChange(id){
        this.editForm.agent_id = id
      },
      deleteUser(index, value) {
        this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          ApicontracthospitalrecordDel(value.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getInfo()
            this.getList()
          }).finally(() => {
            loading.close()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      submit: debounce(function () { //提交  修改或新增
        const options = {
          ...this.editForm
        }
        for (const key of this.rules) {
          if (!options[key] && options[key] !== 0) {
            this.$message({
              type: 'error',
              message: '必填信息请填写完整！'
            });
            return
          }
        }
        this.btnLoading = true
        options.contracts_id = this.contracts_id
        if (options.id) { //有ID就是修改
          ApicontracthospitalrecordPut(options, options.id).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.editFormVisible = false
            this.getInfo()
            this.getList()
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '修改失败!'
            });
          }).finally(() => {
            this.btnLoading = false
          });
        } else {
          ApicontracthospitalrecordAdd(options).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.editFormVisible = false
            this.getList()
            this.getInfo()
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '添加失败!'
            });
          }).finally(() => {
            this.btnLoading = false
          });
        }
      }, 800, true),
    },

  }
</script>